﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using ArchiSimple.Windows.Dao;
using ArchiSimple.Windows.Message;
using ArchiSimple.Windows.Model;
using GalaSoft.MvvmLight.Command;
#if NETFX_CORE
using Windows.UI.Xaml.Controls;
#else
using Microsoft.Win32;
#endif

namespace ArchiSimple.Windows.ViewModel
{
    public class FileViewModel : ViewModelBase
    {
        private Plan currentPlan;

        private PlanDao planDao;

        public FileViewModel(PlanDao planDao)
        {
            this.planDao = planDao;
        }

        public ICommand NewCommand { get; set; }

        public ICommand OpenCommand { get; set; }

        public ICommand SaveCommand { get; set; }

        public override void Init()
        {
            base.Init();

            this.NewCommand = new RelayCommand(() =>
            {
                currentPlan = new Plan();
                this.Send<LoadPlanMessage>(new LoadPlanMessage { Plan = currentPlan });
                this.NavigateTo("Plan");
            });

            this.OpenCommand = new RelayCommand(() =>
            {
#if !NETFX_CORE
                var openFile = new OpenFileDialog();
                openFile.DefaultExt = ".arh";
                openFile.Filter = "ArchiSimple File (.arh)|*.arh";

                var result = openFile.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    currentPlan = this.planDao.Load(openFile.FileName);
                    this.Send<LoadPlanMessage>(new LoadPlanMessage { Plan = currentPlan });
                    this.NavigateTo("Plan");
                }
#endif
            });

            this.SaveCommand = new RelayCommand(() =>
            {
#if !NETFX_CORE
                var saveFile = new SaveFileDialog();
                saveFile.DefaultExt = ".arh";
                saveFile.Filter = "ArchiSimple File (.arh)|*.arh";

                var result = saveFile.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    this.planDao.Save(saveFile.FileName, this.currentPlan);
                    this.NavigateTo("Plan");
                }
#endif
            });
        }
    }
}
